package com.infore;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

@SpringBootApplication
@MapperScan(basePackages={"com.infore.water.mapper"})
@ServletComponentScan
public class WaterApplication {

	public static void main(String[] args) {
		SpringApplication.run(WaterApplication.class, args);
	}
	@Autowired(required=false)
	private Environment env;

	@Bean(name = "waterdataSource")
	public DataSource dataSource() throws SQLException {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(env.getProperty("spring.datasource.url"));
		//用户
		dataSource.setUsername(env.getProperty("spring.datasource.data-username"));
		//密码
		dataSource.setPassword(env.getProperty("spring.datasource.data-password"));
		dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
		dataSource.setInitialSize(2);
		dataSource.setMaxActive(20);
		dataSource.setMinIdle(0);
		dataSource.setMaxWait(60000);
		dataSource.setValidationQuery("SELECT 1 ");
		dataSource.setTestOnBorrow(false);
		dataSource.setTestWhileIdle(true);
		dataSource.setPoolPreparedStatements(false);
		dataSource.setFilters("stat,wall");
		Properties properties = new Properties();
		properties.setProperty("druid.stat.mergeSql","true");
		properties.setProperty("druid.stat.slowSqlMillis","5000");
		dataSource.setConnectProperties(properties);
		return dataSource;
	}

	@Bean
	public JdbcTemplate primaryJdbcTemplate(@Qualifier(value = "waterdataSource") DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}

	@Bean
	public NamedParameterJdbcTemplate primaryNamedParameterJdbcTemplate(@Qualifier(value = "waterdataSource")DataSource dataSource) {
		return new NamedParameterJdbcTemplate(dataSource);
	}
}
